import { Toast } from 'vant';
import auth from '@/service/auth';

function errorHandler(data) {
  const { msg } = data;

  Toast(msg || 'Request error, Please try again later');
}

export default instance => {
  // Add a response interceptor
  instance.interceptors.response.use(response => {
    const data = response.data;
    if (data && data.status === '0') {
      if (data.error === '02000112' || data.error === '02000114' || data.error === '01000114' || data.error === '01000113') {
        auth.expireToLogin();
        return 0;
      }
      // 02000130 第五步拉起人脸
      if (response.config && response.config.showDefaultError !== false && data.error !== '01000116' && data.error !== '02000130') {
        errorHandler({ msg: data.msg });
        return Promise.reject(data) // 抛出异常给上层处理---比如按钮禁用
      }
    }

    return response;
  }, error => {
    // Do something with response error
    const data = {
      error,
      msg: ''
    };

    if (error.response) {
      data.msg = error.response.data && error.response.data.msg;
    } else {
      data.msg = error.message && 'Current network is unavailable，Please check the network!';
    }

    if (error.config && error.config.showDefaultError !== false) {
      errorHandler(data);
    }
    // errorHandler(data);

    return Promise.reject(error);
  });
};
